package leetcode.editor.cn;


/**
 * @description:
 * @author: ywk
 * @date: 2023-11-19
 */
public class P918 {
    public static void main(String[] args) {

        int[] arr = new int[]{-5, -2, 5, 6, -2, -7, 0, 2, 8};
        System.out.println(maxSubarraySumCircular(arr));
    }

    public static int maxSubarraySumCircular(int[] nums) {
        int n = nums.length;
        int[] leftMax = new int[n];
        leftMax[0] = nums[0];
        int leftSum = nums[0];
        int pre = leftSum, res = leftSum;
        for (int i = 1; i < n; i++) {
            //可能只在左边
            pre = Math.max(pre + nums[i], nums[i]);
            res = Math.max(res, pre);
            //左边前缀和
            leftSum += nums[i];
            leftMax[i] = Math.max(leftMax[i - 1], leftSum);
        }
        //右边前缀和
        int rightSum = 0;
        for (int i = n - 1; i > 0; i--) {
            rightSum += nums[i];
            res = Math.max(res, rightSum + leftMax[i - 1]);
        }
        return res;
    }
}
